//
//  SafetyDesktopViewController.m
//  safetyDesktop
//
//  Created by 徐辉 on 2017/3/14.
//  Copyright © 2017年 xuhui. All rights reserved.
//

#import "SafetyDesktopViewController.h"
#import <objc/runtime.h>
#import "PackageInfo.h"
#import "Masonry.h"
#import "SliderController.h"
#import "NavigationController.h"
#import "SVProgressHUD.h"
#import "ASIHTTPRequest.h"
#import "HttpUtil.h"
#import "ApiSupport.h"
#import "AppInfoModel.h"
#import "MBProgressHUD.h"
#define scale [UIScreen mainScreen].bounds.size.width/320
#define CurrentScreenWidth [UIScreen mainScreen].bounds.size.width

@interface SafetyDesktopViewController ()<UIScrollViewDelegate,ASIHTTPRequestDelegate>
{
    UIScrollView *_scrollView;
    NSMutableArray *_appArr;
    UIPageControl *_pageControl;
}

@property(nonatomic,strong) NavigationController *navC;
@property(nonatomic,strong)NSArray * insideAppinfoArray;
@property(nonatomic,strong) MBProgressHUD * hud;
@end

@implementation SafetyDesktopViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateDeskHandler:) name:@"deskupdate" object:nil];
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(skinSwitchHandler) name:@"skinswitch" object:nil];
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[Utils getImageByDevce:@"navigationBar_menu"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemHnadler)];
    
    UIButton *skinButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [skinButton setBackgroundImage:[Utils getImageByDevce:@"navigationBar_skin"] forState:UIControlStateNormal];
    [skinButton sizeToFit];
    [skinButton addTarget:self action:@selector(skinSettingHandler:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:skinButton];

    _scrollView = [[UIScrollView alloc] init];
    _scrollView.frame = [UIScreen mainScreen].bounds;
    _scrollView.pagingEnabled = YES;
    [self.view addSubview:_scrollView];
    _scrollView.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.delegate = self;
    
    self.view.backgroundColor = [UIColor lightGrayColor];
    if ([DeviceTypeJudge isPadDeviceType])
    {
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0.0, 80*scale*4+30*scale, self.view.frame.size.width, 40)];
    }
    else
    {
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0.0, 95*scale*4+30, self.view.frame.size.width, 40)];
    }
    
    _pageControl.hidesForSinglePage = YES;
    _pageControl.userInteractionEnabled = NO;
    [self.view addSubview:_pageControl];
    _appArr = [[NSMutableArray alloc] init];
    _appArr = [self getDesktoPApps];
    [self loadAppInfoList];
}


-(void)loadAppInfoList{
    MBProgressHUD * hud =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud = hud;
    hud.color = [UIColor grayColor];//这儿表示无背景
    //显示的文字
    hud.labelText = @"数据加载中......";
    hud.backgroundColor = [UIColor whiteColor];
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    NSString * url = [ApiSupport getAppStoreList];
   //获得内部应用
    [params setValue:@"2" forKey:@"type"];
    [params setValue:@"1" forKey:@"appType"];
    NSString *insideEncode = [HttpUtil buildUrl:url WithParams:params];
    ASIHTTPRequest *insideEequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:insideEncode]];
    insideEequest.tag = 999;
    //设置网络请求的延时为10秒钟
    insideEequest.timeOutSeconds=10;
    //设置代理
    insideEequest.delegate=self;
    [insideEequest startAsynchronous];
}

//接收到服务器返回的数据时调用
-(void)requestFinished:(ASIHTTPRequest *)request{
    NSArray * tempArray  = [NSJSONSerialization JSONObjectWithData:request.responseData options:0 error:nil];
    NSArray * insideAppinfoArray = [AppInfoModel appInfoArrayWithArray:tempArray];
    self.insideAppinfoArray = insideAppinfoArray;
    for (AppInfoModel * model in insideAppinfoArray) {
        BOOL contain = NO;
        for (PackageInfo * appInfo  in _appArr) {
            if ([appInfo.packageName isEqualToString:model.packageName]) {
                contain = YES;
                break;
            }
        }
        if (([model.appState isEqualToString:@"打开"] && !contain) || ([model.appState isEqualToString:@"更新"] && !contain)) {
            PackageInfo * info = [[PackageInfo alloc]init];
            info.softName = model.name;
            info.packageName = model.packageName;
            info.version = model.version;
            NSString *servAddr = [[UserDefaultsUtil shareInstance]getString:LC_SERVADDR];
            if(![StringUtil isEmpty:servAddr]){
            NSString * iconPathStr = [NSString stringWithFormat:@"http://%@%@",servAddr,model.iconPath];
            NSURL * url = [NSURL URLWithString:iconPathStr];
            info.iconImage = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
             [_appArr addObject:info];
            }
        }
    }
    [self.hud hide:YES afterDelay:0];
    [self configUI];
}

- (void)viewWillAppear:(BOOL)animated
{
    
     _scrollView.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
}

//侧滑栏滑动
- (void)leftBarButtonItemHnadler{
    [[SliderController sharedInstance]leftTapHandler];
}

/**
 *  肤色切换
 */
- (void)skinSwitchHandler{
    self.tabBarItem.selectedImage = [[Utils imageWithKey:@"tabBar_desktop_click_icon"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.view.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    self.navigationController.navigationBar.barTintColor = [Utils colorWithKey:@"mainBgColor"];
    self.navC.cover.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    _scrollView.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
}

- (void)updateDeskHandler:(NSNotification*)notification{
    [_appArr removeAllObjects];
    _appArr = [self getDesktoPApps];
    if (notification.object) {
       self.insideAppinfoArray = notification.object;
    }
        for (AppInfoModel * model in self.insideAppinfoArray) {
            BOOL contain = NO;
            for (PackageInfo * appInfo  in _appArr) {
                if ([appInfo.packageName isEqualToString:model.packageName]) {
                    contain = YES;
                    break;
                }
            }
            if (([model.appState isEqualToString:@"打开"] && !contain) || ([model.appState isEqualToString:@"更新"] && !contain)) {
                PackageInfo * info = [[PackageInfo alloc]init];
                info.softName = model.name;
                info.packageName = model.packageName;
                info.version = model.version;
                NSString *servAddr = [[UserDefaultsUtil shareInstance]getString:LC_SERVADDR];
                if(![StringUtil isEmpty:servAddr]){
                    NSString * iconPathStr = [NSString stringWithFormat:@"http://%@%@",servAddr,model.iconPath];
                    NSURL * url = [NSURL URLWithString:iconPathStr];
                    info.iconImage = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
                    [_appArr addObject:info];
                }
            }
        }
    
 
    dispatch_async(dispatch_get_main_queue(), ^{
            if (_scrollView != nil) {
                [_scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
                    [self configUI];
            }
    });
}
- (void)skinSettingHandler:(UIButton *)sender{
    sender.selected = !sender.selected;
    [[UserDefaultsUtil  shareInstance]saveBoolConfig:SKIN_SWITCH :sender.selected];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"skinswitch" object:nil];
    
}


- (void)configUI
{
        NSInteger count;
        
        if (_appArr.count/16>0 && _appArr.count%16 !=0)
        {
            count = _appArr.count/16+1;
        }
        else if (_appArr.count/16>0 && _appArr.count%16 == 0)
        {
            count = _appArr.count/16;
        }
        else
        {
            count = 1;
        }
        
        _pageControl.numberOfPages = count;
        _scrollView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width*count, 95*scale+30);
        
        
        for (int i = 0; i<_appArr.count; i++) {
            
            UIView *bgView = [[UIView alloc] init];
            bgView.userInteractionEnabled = YES;
            bgView.tag = i;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openApp:)];
            [bgView addGestureRecognizer:tap];
            [_scrollView addSubview:bgView];
        
            [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
                
                if ([DeviceTypeJudge isPadDeviceType])
                {
                    make.height.mas_equalTo(85*scale);
                    make.width.mas_equalTo(77*scale);
                    make.left.mas_equalTo(6*scale+(i%4)*77*scale+(i/16)*CurrentScreenWidth);
                    make.top.mas_equalTo(30*scale+((i%16)/4)*80*scale);
                }
                else
                {
                    make.height.mas_equalTo(85*scale);
                    make.width.mas_equalTo(75*scale);
                    make.left.mas_equalTo(10*scale+(i%4)*75*scale+(i/16)*CurrentScreenWidth);
                    make.top.mas_equalTo(30*scale+((i%16)/4)*95*scale);
                }
                
            }];
            
            PackageInfo *packageInfo = _appArr[i];
            UIImageView *iconImageView = [[UIImageView alloc] init];
            iconImageView.image = packageInfo.iconImage;
            iconImageView.layer.masksToBounds = YES;
            iconImageView.layer.cornerRadius = 12;
            iconImageView.userInteractionEnabled = YES;
            [bgView addSubview:iconImageView];
            
            if ([DeviceTypeJudge isPadDeviceType])
            {
                [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.mas_equalTo(bgView).offset(2);
                    make.left.mas_equalTo(bgView).offset((75*scale-70)/2);
                    make.height.mas_equalTo(70);
                    make.width.mas_equalTo(70);
                }];
                
            }
            else
            {
                [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.mas_equalTo(bgView).offset(2);
                    make.left.mas_equalTo(bgView).offset((75*scale-54)/2);
                    make.height.mas_equalTo(54);
                    make.width.mas_equalTo(54);
                }];
                
            }
            UILabel *titleLabel = [[UILabel alloc] init];
            titleLabel.textAlignment = NSTextAlignmentCenter;
            titleLabel.textColor = [UIColor whiteColor];
            titleLabel.userInteractionEnabled = YES;
            titleLabel.font = [UIFont systemFontOfSize:12.0f];
            titleLabel.text = packageInfo.softName;
            [bgView addSubview:titleLabel];
            [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(bgView).offset(65);
                make.left.mas_equalTo(bgView).offset(0);
                make.height.mas_equalTo(20*scale);
                make.width.mas_equalTo(77*scale);
                
                
            }];
            
        }
        
        [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self.view);
            
        }];
    
}

- (void)openApp:(UITapGestureRecognizer *)sender
{
    NSInteger index = sender.view.tag;
    PackageInfo *packageInfo = _appArr[index];
    
    Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");
    NSObject *workspace = [LSApplicationWorkspace_class performSelector:@selector(defaultWorkspace)];
    //通过Bundle打开app
    [workspace performSelector:NSSelectorFromString(@"openApplicationWithBundleID:") withObject:packageInfo.packageName];
}

- (UIImage *)iconImage:(id)app
{
    
    NSData *iconData = [app performSelector:NSSelectorFromString(@"iconDataForVariant:") withObject:@(2)];
#pragma clang diagnostic pop
    
    NSInteger lenth = iconData.length;
    NSInteger width = 87;
    NSInteger height = 87;
    
    uint32_t *pixels = (uint32_t *)malloc(width * height * sizeof(uint32_t));
    [iconData getBytes:pixels range:NSMakeRange(32, lenth - 32)];
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(pixels,
                                             width,
                                             height,
                                             8,
                                             (width + 1) * sizeof(uint32_t),
                                             colorSpace,
                                             kCGBitmapByteOrder32Little |
                                             kCGImageAlphaPremultipliedFirst);
    
    CGImageRef cgImage = CGBitmapContextCreateImage(ctx);
    CGContextRelease(ctx);
    CGColorSpaceRelease(colorSpace);
    UIImage *icon = [UIImage imageWithCGImage: cgImage];
    CGImageRelease(cgImage);
    
    return icon;
}

//获取用户安装的app信息
- (NSMutableArray *)getAllAppsFromDevice
{
    NSMutableArray *app = [NSMutableArray array];
    //获取手机上所有的app
    Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");
    NSObject *workspace = [LSApplicationWorkspace_class performSelector:@selector(defaultWorkspace)];
    NSArray *apps = [workspace performSelector:@selector(allInstalledApplications)];
    Class LSApplicationProxy_class = objc_getClass("LSApplicationProxy");
    for (int i = 0; i < apps.count; i++) {
        NSObject *temp = apps[i];
        if ([temp isKindOfClass:LSApplicationProxy_class]) {
            NSString *appBundleId = [temp performSelector:NSSelectorFromString(@"applicationIdentifier")];
            NSString *appName = [temp performSelector:NSSelectorFromString(@"localizedName")];
            
            NSString *appVersion = [temp performSelector:NSSelectorFromString(@"shortVersionString")];
            NSInteger appSize = [temp performSelector:NSSelectorFromString(@"description")];
            NSString * type = [temp performSelector:NSSelectorFromString(@"applicationType")];
            
            if ([type isEqualToString:@"User"] && ![appBundleId isEqualToString:@"cn.neiwang.emm"]) {
                PackageInfo *packageInfo = [[PackageInfo alloc]init];
                packageInfo.softName = appName;
                packageInfo.packageName = appBundleId;
                packageInfo.iconImage = [self iconImage:temp];
                packageInfo.version = appVersion;
                packageInfo.size = 0;
                [app addObject:packageInfo];
            }
        }
    }
    return app;
}


- (NSMutableArray *)getDesktoPApps{
    
    NSMutableArray *apps = [self getAllAppsFromDevice];
    NSMutableArray *appsTemp = [NSMutableArray array];
    NSString *appsStr = [[UserDefaultsUtil shareInstance]getString:LC_DESKTOPAPPS];
    NSArray *appsArr = [appsStr componentsSeparatedByString:@";"];
    for (int i = 0; i < appsArr.count; i++) {
        for (PackageInfo *packInfo in apps) {
             NSString *softName = packInfo.softName;
            if ([appsArr[i] containsString:@"*"]) {
                NSString *tmpItem = [[appsArr[i] stringByReplacingOccurrencesOfString:@"*" withString:@""] lowercaseString];
                if ([[softName lowercaseString] containsString:tmpItem] || (softName != nil && [[softName lowercaseString] isEqualToString:tmpItem])) {
                        [appsTemp addObject:packInfo];
                }
            }else{
                NSString *tmpItem = [appsArr[i] lowercaseString];
                if ([[softName lowercaseString] containsString:tmpItem] || (softName != nil && [[softName lowercaseString] isEqualToString:tmpItem])) {
                      [appsTemp addObject:packInfo];
                }
            }
        }
    }
    
    NSMutableArray * tempArray = [NSMutableArray array];
    for (int i = 0; i< appsTemp.count; i++) {
        PackageInfo *packInfo = appsTemp[i];
        if (![tempArray containsObject:packInfo]) {
             [tempArray addObject:packInfo];
        }
    }
    return tempArray;
}

#pragma mark -
#pragma mark UIScrollView
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if ([scrollView isKindOfClass:[UITableView class]]) {
        return;
    }
    
    int index = fabs(scrollView.contentOffset.x) / scrollView.frame.size.width;
    
    _pageControl.currentPage = index;
    //index为当前页码
    NSLog(@"%d",index);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
